﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;

namespace NETXPF.Library
{
	public class IOUtils
	{
		/// <summary>
		/// Reads the contents of a stream reliably
		/// </summary>
		/// <param name="stream"></param>
		/// <returns></returns>
		public static byte[] ReadFully(Stream stream)
		{
			byte[] buffer = new byte[4096];
			using (MemoryStream ms = new MemoryStream())
			{
				while (true)
				{
					int read = stream.Read(buffer, 0, buffer.Length);
					if (read <= 0)
						return ms.ToArray();
					ms.Write(buffer, 0, read);
				}
			}
		}

		/// <summary>
		/// Determines if GZip is supported
		/// </summary>
		/// <returns></returns>
		public static bool IsGZipSupported(HttpContext context)
		{
			string AcceptEncoding = context.Request.Headers["Accept-Encoding"];
			if (!string.IsNullOrEmpty(AcceptEncoding) &&
				 (AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate")))
				return true;
			return false;
		}

		/// <summary>
		/// Sets up the current page or handler to use GZip through a Response.Filter
		/// IMPORTANT:  
		/// You have to call this method before any output is generated!
		/// </summary>
		public static void GZipEncodePage(HttpContext context)
		{
			HttpResponse Response = context.Response;
			if (IsGZipSupported(context) && Response.Filter != null &&
				(!(Response.Filter is System.IO.Compression.GZipStream)) &&
				(!(Response.Filter is System.IO.Compression.DeflateStream)))
			{
				string AcceptEncoding = context.Request.Headers["Accept-Encoding"];
				if (AcceptEncoding.Contains("gzip"))
				{
					Response.Filter = new System.IO.Compression.GZipStream(Response.Filter,
											  System.IO.Compression.CompressionMode.Compress);
					Response.AppendHeader("Content-Encoding", "gzip");
				}
				else if (AcceptEncoding.Contains("deflate"))
				{
					Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter,
											  System.IO.Compression.CompressionMode.Compress);
					Response.AppendHeader("Content-Encoding", "deflate");
				}
			}
			Response.AppendHeader("Vary", "Content-Encoding");
		}
	}
}
